package com.stockz.equity.charting.view.widget;

import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import com.stockz.equity.charting.event.EventPublisher;
import com.stockz.equity.charting.event.RepaintStockChartPanelEvent;
import com.stockz.equity.charting.model.Shape;
import com.stockz.equity.charting.view.StockChart;
import com.stockz.equity.charting.view.StockChartView;
import com.stockz.equity.charting.view.toolbar.DrawingToolbar;
import com.stockz.equity.pattern.Child;

@Component
public class UndoDrawingButton extends JButton implements Child, Ordered {
	private static final long serialVersionUID = 2962831734160263276L;

	@SuppressWarnings("unchecked")
	private List<Class> parentList = new ArrayList<Class>(1);
	@Autowired StockChartView stockChartView;
	
	public UndoDrawingButton(){
		//super(new ImageIcon("src/com/stockz/equity/resource/image/undo.jpg"));
		super(new ImageIcon(new ImageIcon("src/com/stockz/equity/resource/image/undo.jpg")
		.getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH)));
		parentList.add(DrawingToolbar.class);
		addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				Iterator<Shape> iterator = stockChartView.getSelectedStockChart().getStockChartPanel()
				.getStockChartPanelState().getShapeSet().iterator();
				Shape shape = null;
				Shape targetShape = null;
				while(iterator.hasNext()){
					shape = iterator.next();
					if(shape.isVisible()){
						targetShape = shape;
					}
				}
				if(targetShape != null){
					targetShape.setVisible(false);					
					EventPublisher.publishEvent(
							new RepaintStockChartPanelEvent(
									stockChartView.getSelectedStockChart().getStockChartPanel()));
				}
			}
			
		});
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Collection<Class> getParents() {
		return parentList;
	}

	@Override
	public int getOrder() {
		return 0;
	}
}
